//
//  TL_CancelAccountViewController.m
//  WXReader
//
//  Created by Andrew on 2019/12/21.
//  Copyright © 2019 Andrew. All rights reserved.
//

#import "TL_CancelAccountViewController.h"
#import "TL_WebViewViewController.h"
#import "AppDelegate.h"
#import "TL_CancelAccountModel.h"
#import "TL_ViewHelper.h"

#import "TL_CancelAccountTableViewCell.h"

@interface TL_CancelAccountViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) UIButton *agreementButton;

@property (nonatomic, strong) UIButton *applyButton;


@property (nonatomic, strong) TL_CancelAccountModel *indexModel;

@property (nonatomic, assign) CGFloat titleHeight;

@end

@implementation TL_CancelAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialize];
    [self netRequest];
}

- (void)initialize
{
    [self setNavigationBarTitle:self.navTitle ?: WXLocalizedString(@"删除账号")];
}

- (void)createSubviews
{
    if (self.indexModel.status == 0) {
        self.applyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.applyButton.alpha = 0.6;
        self.applyButton.backgroundColor = kRedColor;
        [self.applyButton setTitle:WXLocalizedString(@"申请注销") forState:UIControlStateNormal];
        [self.applyButton addTarget:self action:@selector(applyClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.applyButton];
        
        [self.applyButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(- PUB_TABBAR_OFFSET);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.height.mas_equalTo(PUB_TABBAR_HEIGHT - PUB_TABBAR_OFFSET);
        }];
        
        UIView *bottomView = [TL_UIFactory viewWithBackgroundColor:self.applyButton.backgroundColor cornerRadius:0.0];
        [bottomView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(applyClick)]];
        bottomView.alpha = self.applyButton.alpha;
        [self.applyButton addObserverBlockForKeyPath:KEY_PATH(self.applyButton, alpha) block:^(id  _Nonnull obj, id  _Nullable oldVal, id _Nullable newVal) {
            bottomView.alpha = [newVal floatValue];
        }];
        [self.view addSubview:bottomView];
        
        [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.applyButton.mas_bottom);
            make.left.right.equalTo(self.applyButton);
            make.bottom.equalTo(self.view);
        }];
        
        self.mainTableView.delegate = self;
        self.mainTableView.dataSource = self;
        [self.mainTableView setTableHeaderView:self.headerView];
        [self.mainTableView setTableFooterView:[self footerView]];
        [self.view addSubview:self.mainTableView];
        
        [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.top.mas_equalTo(PUB_NAVBAR_HEIGHT);
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.bottom.equalTo(self.applyButton.mas_top);
        }];
        
        [self.mainTableView reloadData];
    } else {
        UIScrollView *mainScrollView = [TL_UIFactory scrollView];
        mainScrollView.contentInset = UIEdgeInsetsMake(0, 0, PUB_TABBAR_OFFSET, 0);
        [self.view addSubview:mainScrollView];
        
        UIView *mainView = [TL_UIFactory view];
        [mainScrollView addSubview:mainView];
        
        UIImageView *topImageView = [TL_UIFactory imageViewWithBackgroundColor:nil image:[[UIImage imageNamed:@"public_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] cornerRadius:0.0];
        topImageView.tintColor = RGB(96, 193, 2);
        [mainView addSubview:topImageView];
        
        UILabel *titleLabel = [TL_UIFactory labelWithBackgroundColor:nil font:kMainFont textColor:kBlackColor];
        titleLabel.numberOfLines = 0;
        titleLabel.preferredMaxLayoutWidth = kScreenWidth - 2 * kMoreHalfMargin;
        titleLabel.text = self.indexModel.give_up_title ?: @"";
        [mainView addSubview:titleLabel];
        
        UILabel *tipsLabel = [TL_UIFactory labelWithBackgroundColor:nil font:BOLD_SYSTEM_FONT(14) textColor:kBlackColor];
        tipsLabel.numberOfLines = 0;
        tipsLabel.preferredMaxLayoutWidth = kScreenWidth - 2 * kMoreHalfMargin;
        tipsLabel.text = self.indexModel.give_up_desc ?: @"";
        [mainView addSubview:tipsLabel];
        
        UIButton *confirmButton = [TL_UIFactory buttonWithTarget:self action:@selector(cancelLogout)];
        [confirmButton setTitle:WXLocalizedString(@"确认放弃注销") forState:UIControlStateNormal];
        [confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        confirmButton.titleLabel.font = BOLD_SYSTEM_FONT(14);
        confirmButton.backgroundColor = kRedColor;
        confirmButton.layer.cornerRadius = 45.0 / 2.0;
        [mainView addSubview:confirmButton];
        
        
        [mainScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(PUB_NAVBAR_HEIGHT);
            make.left.right.bottom.equalTo(self.view);
        }];
        
        [mainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.width.equalTo(mainScrollView);
        }];
        
        [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.navigationBar.mas_bottom).offset(kMargin);
            make.centerX.equalTo(self.view);
            make.width.height.mas_equalTo(75.0);
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topImageView.mas_bottom).offset(kMoreHalfMargin);
            make.left.right.equalTo(self.view).inset(kMoreHalfMargin);
            make.height.mas_equalTo(titleLabel.w_textHeight);
        }];
        
        [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(titleLabel.mas_bottom).offset(25.0);
            make.left.right.equalTo(titleLabel);
            make.height.mas_equalTo(tipsLabel.w_textHeight);
        }];
        
        [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(tipsLabel.mas_bottom).offset(25.0);
            make.left.right.equalTo(tipsLabel);
            make.height.mas_equalTo(confirmButton.layer.cornerRadius * 2.0);
            make.bottom.equalTo(mainView).priorityLow();
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellName = @"TL_CancelAccountTableViewCell";
    TL_CancelAccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[TL_CancelAccountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }
    cell.titleString = [self.dataSourceArray objectAtIndex:indexPath.row][0];
    cell.detailString = [self.dataSourceArray objectAtIndex:indexPath.row][1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//section头间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.titleHeight + kMargin;
}
//section头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kLabelHeight + kMargin)];
    view.backgroundColor = [UIColor clearColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kHalfMargin, kMargin, SCREEN_WIDTH - 2 * kHalfMargin, self.titleHeight)];
    titleLabel.text = self.indexModel.title ?: @"";
    titleLabel.textColor = kBlackColor;
    titleLabel.font = BOLD_SYSTEM_FONT(15);
    titleLabel.numberOfLines = 0;
    titleLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - kHalfMargin * 2;
    [view addSubview:titleLabel];
    
    return view;
}

- (UIView *)footerView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kLabelHeight + kHalfMargin)];
    view.backgroundColor = [UIColor clearColor];
    
    if (!self.agreementButton) {
        self.agreementButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.agreementButton.frame = CGRectMake(kHalfMargin, kHalfMargin, 30, 30);
        self.agreementButton.selected = NO;
        self.agreementButton.adjustsImageWhenHighlighted = NO;
        [self.agreementButton setImageEdgeInsets:UIEdgeInsetsMake(7, 0, 7, 14)];
        [self.agreementButton setImage:[UIImage imageNamed:@"public_unselect"] forState:UIControlStateNormal];
        [self.agreementButton setImage:[UIImage imageNamed:@"public_selected"] forState:UIControlStateSelected];
        [self.agreementButton addTarget:self action:@selector(agreementClick) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:self.agreementButton];
        
        MK_WEAK_SELF
        NSString *acceptTitle = [NSString stringWithFormat:@"《%@》", self.indexModel.accept_title];
        NSString *acceptString = [NSString stringWithFormat:@"%@%@", self.indexModel.accept_protocol, acceptTitle];
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:acceptString];
        text.lineSpacing = 5;
        text.font = kMainFont;
        [text setTextHighlightRange:NSMakeRange(self.indexModel.accept_protocol.length, acceptTitle.length) color:kMainColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
            vc.navTitle = acceptTitle;
            AppDelegate *delegate = (AppDelegate *)kRCodeSync([UIApplication sharedApplication].delegate);
//            vc.URLString = delegate.checkSettingModel.protocol_list.logoff ?: [NSString stringWithFormat:@"%@%@?packageName=%@", APIURL, Log_Off, [[NSBundle mainBundle] bundleIdentifier]];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        [text setTextHighlightRange:NSMakeRange(0, self.indexModel.accept_protocol.length) color:kBlackColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            [weakSelf agreementClick];
        }];

        YYLabel *tipsLabel = [[YYLabel alloc] init];
        YYTextLayout *textLayout = [YYTextLayout layoutWithContainerSize:CGSizeMake(SCREEN_WIDTH - (kMargin + 30 + kQuarterMargin), CGFLOAT_MAX) text:text];
        tipsLabel.frame = CGRectMake(kMargin + 10, kHalfMargin, SCREEN_WIDTH - (kMargin + 30 + kQuarterMargin), textLayout.textBoundingSize.height);
        tipsLabel.centerY = self.agreementButton.centerY;
        tipsLabel.numberOfLines = 0;
        tipsLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - (kMargin + 30 + kQuarterMargin);
        tipsLabel.attributedText = text;
        tipsLabel.textAlignment = NSTextAlignmentLeft;
        tipsLabel.userInteractionEnabled = YES;
        [view addSubview:tipsLabel];
        
        view.height = tipsLabel.height + kMargin;
    }
    
    return view;
}

- (UIView *)headerView
{
    if (!_headerView) {
        
        NSString *str = self.indexModel.notice ?: @"";
        
        _headerView = [[UIView alloc] init];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, [TL_ViewHelper getDynamicHeightWithLabelFont:kMainFont labelWidth:(SCREEN_WIDTH - (kMargin + kHalfMargin)) labelText:str] + 80 + 2 * kMargin);
        _headerView.backgroundColor = kWhiteColor;
        
        UIView *headerBackView = [[UIView alloc] init];
        headerBackView.backgroundColor = kGrayViewColor;
        headerBackView.layer.cornerRadius = 12;
        [_headerView addSubview:headerBackView];
        
        [headerBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(kHalfMargin);
            make.top.mas_equalTo(kHalfMargin);
            make.width.mas_equalTo(SCREEN_WIDTH - kMargin);
            make.height.mas_equalTo(_headerView.mas_height).with.offset(- kHalfMargin);
        }];
        
        UIImageView *headerImageView = [[UIImageView alloc] init];
        headerImageView.image = [UIImage imageNamed:@"mine_cancel_account"];
        [_headerView addSubview:headerImageView];
        
        [headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kMargin);
            make.centerX.mas_equalTo(_headerView.mas_centerX);
            make.width.height.mas_equalTo(80);
        }];
        
        UILabel *headerLabel = [[UILabel alloc] init];
        headerLabel.numberOfLines = 0;
        headerLabel.font = kMainFont;
        headerLabel.textColor = RGB(96, 106, 100);
        [_headerView addSubview:headerLabel];
        
        [headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(kMargin + kHalfMargin);
            make.top.mas_equalTo(headerImageView.mas_bottom).with.offset(kHalfMargin);
            make.width.mas_equalTo(SCREEN_WIDTH - 2 * (kMargin + kHalfMargin));
            make.height.mas_equalTo([TL_ViewHelper getDynamicHeightWithLabelFont:kMainFont labelWidth:(SCREEN_WIDTH - (kMargin + kHalfMargin)) labelText:str]);
        }];
        
        NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithAttributedString:[[NSAttributedString alloc] initWithString:str]];
        headerLabel.attributedText = attributeString;
    }
    return _headerView;
}

- (void)agreementClick
{
    self.agreementButton.selected = !self.agreementButton.selected;
    
    if (self.agreementButton.selected) {
        self.applyButton.alpha = 1;
    } else {
        self.applyButton.alpha = 0.6;
    }
}

- (void)netRequest {
    MK_WEAK_SELF
//    [TL_NetworkRequestManger POST:Cancel_Account_Index parameters:nil model:TL_CancelAccountModel.class success:^(BOOL isSuccess, TL_CancelAccountModel * _Nullable t_model, TL_NetworkRequestModel * _Nonnull requestModel) {
//        if (isSuccess) {
//            if (t_model.status == 0) {
//                [weakSelf setNavigationBarTitle:weakSelf.navTitle ?: WXLocalizedString(@"删除账号")];
//            } else {
//                [weakSelf setNavigationBarTitle:WXLocalizedString(@"放弃注销")];
//            }
//            
//            weakSelf.indexModel = t_model;
//            weakSelf.titleHeight = [TL_ViewHelper calcTextSize:CGSizeMake(SCREEN_WIDTH - kHalfMargin * 2, CGFLOAT_MAX)
//                                                            text:t_model.title ?: @""
//                                                   numberOfLines:0
//                                                            font:kBoldFont15
//                                                   textAlignment:NSTextAlignmentLeft
//                                                   lineBreakMode:NSLineBreakByWordWrapping
//                                              minimumScaleFactor:0
//                                                    shadowOffset:CGSizeZero].height;
//            for (TL_CancelAccountListModel *obj in t_model.list) {
//                [weakSelf.dataSourceArray addObject:@[obj.title ?: @"", obj.desc ?: @""]];
//            }
//            [weakSelf createSubviews];
//        } else {
//            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
//        [TL_TopAlertManager showAlertWithError:error defaultText:WXLocalizedString(@"请求失败")];
//    }];
}

- (void)applyClick
{
    if (self.agreementButton.selected) {
        MK_WEAK_SELF
//        [TL_NetworkRequestManger POST:User_Cancel_Account parameters:nil model:nil success:^(BOOL isSuccess, id  _Nullable t_model, TL_NetworkRequestModel * _Nonnull requestModel) {
//            if (isSuccess) {
//                [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"注销账号申请已提交")];
//                
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [weakSelf popViewController];
//                });
//            } else {
//                [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            [TL_TopAlertManager showAlertWithError:error defaultText:nil];
//        }];
    }
}

/// 用户点击放弃注销时调用
- (void)cancelLogout {
    MK_WEAK_SELF
//    [TL_NetworkRequestManger POST:@"/cancel/recall-cancel" parameters:nil model:nil success:^(BOOL isSuccess, id  _Nullable t_model, TL_NetworkRequestModel * _Nonnull requestModel) {
//        if (isSuccess) {
//            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"注销账号申请已取消")];
//            
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [weakSelf.navigationController popViewControllerAnimated:YES];
//            });
//        } else {
//            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
//        [TL_TopAlertManager showAlertWithError:error defaultText:nil];
//    }];
}

@end
